<!--  用户管理 -->
<template>
  <div>
    <div class="flex">
      <div class="flex-left">
        <div class="navigationBar">
          <label>组织机构</label>
          <span @click="showFolder()"
            ><i class="el-icon el-icon-circle-plus"></i
          ></span>
        </div>
        <div class="flex-tree" :key="keyRandom">
          <el-tree
            ref="tree"
            :data="data"
            node-key="id"
            :render-content="renderContent"
            @node-click="handleNodeClick"
            :highlight-current="true"
            :expand-on-click-node="false"
          >
          </el-tree>
        </div>
      </div>
      <div class="flex-right">
        <navigation-bar>
          <div class="searchContent">
            <!-- <el-input
              v-model="username"
              placeholder="请输入姓名/帐号"
              size="mini"
              style="width: 150px; margin-right: 10px"
              @keyup.enter.native="searchClick"
            ></el-input> -->
            <!-- <custom-button
              type="search"
              style="margin-right: 10px"
              @searchClick="searchClick"
            ></custom-button>
            <custom-button
              type="reset"
              style="margin-right: 10px"
              @resetClick="resetClick"
            ></custom-button> -->
            <custom-button
              type="add"
              style="margin-right: 10px"
              @addClick="addClick"
            ></custom-button>
          </div>
        </navigation-bar>
        <table-index
          :dataSource="dataSource"
          :tableColumns="tableColumns"
          :btnList="btnList"
          :pageSize="pageSize"
          :pageCount="pageCount"
          :pageNo="pageNo"
          @pageChange="pageChange"
          @editRow="editRow"
          @viewRow="viewRow"
          @deleteRow="deleteRow"
          @resetPwdRow="resetPwdRow"
          selection
          @handleSelectionChange="handleSelectionChange"
        ></table-index>
      </div>
    </div>
    <div v-if="dialogShow">
      <custom-dialog
        :title="dialogTitle"
        size="large"
        @dialogClose="dialogClose"
      >
        <form-index
          :formConfig="type == 'add' ? formConfigAdd : formConfig"
          @submit="submit"
          :type="type"
          @formInputChange="formInputChange"
          ref="form"
        >
        </form-index>
      </custom-dialog>
    </div>
    <div v-if="dialogFolderShow">
      <custom-dialog
        :title="dialogFolderTitle"
        size="large"
        @dialogClose="dialogFolderClose"
      >
        <form-index
          :formConfig="formConfigFolder"
          @submit="folderSubmit"
          :type="typeFolder"
          @formInputChange="formInputFolderChange"
          ref="form"
        >
        </form-index>
      </custom-dialog>
    </div>

    <div v-if="dialogFolderEditShow">
      <custom-dialog
        title="编辑用户管理"
        size="large"
        @dialogClose="dialogFolderEditShow = false"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="帐号" prop="uLoginName">
                <el-input v-model="form.uLoginName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="uRealName">
                <el-input v-model="form.uRealName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="组织机构" prop="parentId">
                <treeSelect
                  :treeProps="props"
                  :options="treeSelectList"
                  v-model="form.parentId"
                  :clearable="isClearable"
                  :accordion="isAccordion"
                  :expandNode="false"
                  size="small"
                  width="100%"
                  @getValue="getValue($event)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-select
                  v-model="form.sex"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    :label="item.label"
                    :value="item.value"
                    v-for="item in sexlist"
                    v-bind:key="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">确定</el-button>
          </el-form-item>
        </el-form>
      </custom-dialog>
    </div>
  </div>
</template>

<script>
import { resourceFolderForm } from "@/assets/form/managementCenter/resourceFolderForm";
import { userManageAddForm } from "@/assets/form/managementCenter/systemManage/userManageAddForm";
import { userManageForm } from "@/assets/form/managementCenter/systemManage/userManageForm";
import customDialog from "@/components/customComponents/customDialog";
import customButton from "@/components/customComponents/customForm/customButton";
import formIndex from "@/components/customComponents/customForm/formIndex";
import tableIndex from "@/components/customComponents/customeTable/tableIndex";
import navigationBar from "@/components/customComponents/managementCenter/navigationBar";
import treeSelect from "@/components/customComponents/treeSelect";
import { AjaxCommon } from "@/libs/apiCommon";
import { PopupCommon } from "@/libs/popupCommon";
import { SessionCommon } from "@/libs/sessionCommon";
import { Utility } from "@/libs/utility";
export default {
  components: {
    navigationBar,
    customButton,
    tableIndex,
    formIndex,
    customDialog,
    treeSelect,
  },
  data() {
    return {
      oldUserData: {},
      dialogFolderEditShow: false,
      treeSelectList: [],
      sexlist: Utility.getDictList("sex"),
      rules: {
        parentId: [
          {
            required: true,
            message: "请选择组织机构",
            trigger: ["blur", "change"],
          },
          // {min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur"}
        ],
        uLoginName: [
          {
            required: true,
            message: "帐号不能为空",
            trigger: ["blur", "change"],
          },
        ],
        uRealName: [
          {
            required: true,
            message: "姓名不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
      form: {
        parentId: "",
        // 帐号
        uLoginName: "",
        // 账户id
        uID: "",
        // 姓名
        uRealName: "",
        // 性别
        sex: "",
      },
      props: {
        // 配置项（必选）
        id: "id",
        label: "label",
        pid: "parentId",
        children: "children",
        // disabled:true
      },
      keyRandom: "1",
      folderData: null,
      fatherFolderId: "0",
      dialogFolderTitle: "新增机构",
      formConfigFolder: resourceFolderForm,
      typeFolder: "add",
      dialogFolderShow: false,
      version: "",
      data: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      tableIndex: "",
      tableList: [
        {
          id: "1",
          name: "湘江新城1",
        },
        {
          id: "2",
          name: "湘江新城2",
        },
        {
          id: "3",
          name: "湘江新城3",
        },
      ],
      selectItem: [],
      username: "",
      // table 相关参数  begin
      dataSource: [],
      tableColumns: [
        {
          prop: "LoginName",
          label: "帐号",
        },
        {
          prop: "RealName",
          label: "姓名",
        },
        {
          prop: "Sex",
          label: "性别",
          width: 120,
          dictName: "sex",
        },
        // {
        // 	prop: "usertel",
        // 	label: "手机号",
        // },
        {
          prop: "CreateTime",
          label: "创建时间",
        },
      ],
      // btnList: ["edit", "delete", "resetPwd"],
      btnList: ["edit", "delete"],
      pageSize: 20,
      pageCount: 100,
      pageNo: 1,
      // table 相关参数  end

      // 弹窗是否显示
      dialogShow: false,
      // 弹窗标题 (新增修改不同)
      dialogTitle: "",

      // form的配置信息
      formConfig: userManageForm,
      type: "add",

      // form的配置信息
      formConfigAdd: userManageAddForm,
    };
  },
  methods: {
    onSubmit() {
      let self = this;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 原始的部门id和主键id  DepartmentId  Id
          const oldDepartmentId = self.oldUserData.DepartmentId;
          const oldId = self.oldUserData.Id;
          console.log(oldDepartmentId, oldId);

          var d = self.form;
          const parentId = d.parentId;
          d.DepartmentId = d.parentId;
          const id = d.uID;
          delete d.parentId;
          AjaxCommon(
            `/api/UserTissueRelation/Delete?TissueID=${oldDepartmentId}&UserID=${id}`,
            "delete",
            {
              optReason: d.optReason,
            }
          ).then((rr) => {
            console.log(rr);
            AjaxCommon("/api/User/Put", "put", d)
              .then((res) => {
                if (res.data.status == 200) {
                  var params = {
                    UserId: id,
                    TissueID: parentId,
                  };
                  AjaxCommon("/api/UserTissueRelation", "postForm", params);

                  PopupCommon.notify("success", "操作成功");
                  self.initPage();
                  self.dialogFolderEditShow = false;
                } else {
                  PopupCommon.notify("error", res.data.msg);
                }
              })
              .catch((err) => {
                PopupCommon.notify("error", err.message);
              });
          });
        }
      });
    },
    edit(e) {
      console.log(e);
    },
    dialogFolderClose() {
      this.dialogFolderShow = false;
    },
    folderSubmit(d) {
      let self = this;
      var params = {
        FolderName: d.FolderName,
        FatherFolderId: self.fatherFolderId,
        FolderType: 4,
      };
      var titleOpr = "新增成功";
      if (d.Id) {
        params["Id"] = d.Id;
        titleOpr = "编辑成功";
      }
      AjaxCommon(`/api/folder`, "postForm", params)
        .then((res) => {
          if (res.data.status == 200) {
            PopupCommon.notify("success", titleOpr);
            if (self.fatherFolderId != "0") {
              const newChild = {
                id: res.data.response,
                label: d.FolderName,
                children: [],
              };
              if (!self.folderData.children) {
                this.$set(self.folderData, "children", []);
              }
              self.folderData.children.push(newChild);
            }
            self.initLeftFolder(() => {
              // self.initPage()
              if (self.fatherFolderId != "0") {
                const newChild = {
                  id: Math.random(),
                  label: d.FolderName,
                  children: [],
                };
                if (!self.folderData.children) {
                  this.$set(self.folderData, "children", []);
                }
                self.folderData.children.push(newChild);
              }
            });
            self.dialogFolderClose();
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        })
        .catch((err) => {
          PopupCommon.notify("error", err.message);
        });
    },
    showFolder() {
      this.fatherFolderId = "0";
      this.typeFolder = "add";
      this.dialogFolderTitle = "新增机构";
      this.dialogFolderShow = true;
    },
    deleteFolder(item) {
      let self = this;
      const id = item.Id;
      PopupCommon.confirm(`确定删除【${item.FolderName}】？`)
        .then(() => {
          AjaxCommon("/api/familyfolder/Delete?id=" + id, "delete", {
            optReason: "删除",
          }).then((res) => {
            if (res.data.status == 200) {
              PopupCommon.notify("success", "删除成功");
              self.initLeftFolder();
              self.dialogFolderClose();
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          });
        })
        .catch(() => {
          console.log("取消");
        });
    },
    // 懒加载获取树形结构
    loadNode(node, resolve) {
      if (node.level == 0) {
        // node其实是需要展开树节点，但是第一次的node是个无用的数据，可以认为这个node是element给我们创建的，判断的话，就是level等于0
        this.getTreeData(0, resolve);
      } else {
        this.getTreeData(node, resolve);
      }
    },
    // 获取树形结构的数据
    getTreeData(node, resolve) {
      var searchNodeID = node ? node.data.id : null;
      AjaxCommon(
        `/api/folder?folderType=4&key=${searchNodeID}`,
        "get",
        null
      ).then((res) => {
        if (res.data.status == 200) {
          var data = res.data.response;
          data = data.map((r) => {
            return {
              id: r.Id,
              label: r.FolderName,
              children: [],
            };
          });
          if (!node) {
            return resolve(data); // resolve是一个函数，它会接受一个数组，作为你要展开的节点的孩子节点，如果没有孩子节点，直接传一个空数组
          } else {
            if (data && data.length > 0) {
              return resolve(data); // 如果需要设置一个树节点，也可以在这里设置，比如说设置这个孩子节点是叶子节点（也就是不能展开的末节点），可以给其中的数据设置item.isLeaf = true
            } else {
              return resolve([]);
            }
          }
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    append(data) {
      this.folderData = data;
      this.fatherFolderId = data.id;
      this.typeFolder = "add";
      this.dialogFolderTitle = "新增机构";
      this.dialogFolderShow = true;
    },
    remove(node, data) {
      console.log(node, data, "......................data");
      let self = this;
      const id = data.id;
      PopupCommon.confirm(`确定删除【${data.label}】？`)
        .then(() => {
          AjaxCommon("/api/folder/Delete?id=" + id, "delete", {
            optReason: "删除",
          }).then((res) => {
            self.keyRandom = parseInt(Math.random() * 10000);
            if (res.data.status == 200) {
              PopupCommon.notify("success", "删除成功");
              this.initLeftFolder(() => {
                this.initPage();
              });
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          });
        })
        .catch(() => {
          console.log("取消");
        });
    },
    renderContent(h, { node, data }) {
      // 删除按钮，暂时隐藏。放在tree-btn  类里面
      return (
        <span style="flex: 1;display: flex;align-items: center;justify-content: space-between;font-size: 14px;padding-right: 8px;">
          <span>{node.label}</span>
          <span class="tree-btn">
            <span style="color: #409EFF;padding: 2px;border-radius: 2px;margin-right: 4px;">
              <i class="el-icon-plus" on-click={() => this.append(data)}></i>
            </span>
            {/* <span style="color: #409EFF;padding: 2px;border-radius: 2px;margin-right: 4px;">
              <i class="el-icon-edit" on-click={() => this.edit(data)}></i>
            </span> */}
            <span style="padding: 2px;color: red;border-radius: 2px;">
              <i
                class="el-icon-delete"
                on-click={() => this.remove(node, data)}
              ></i>
            </span>
          </span>
        </span>
      );
    },
    initLeftFolder(callback) {
      let self = this;
      self.data = [];
      AjaxCommon("/api/folder/GetFullFolder?FolderType=4", "get", null).then(
        (res) => {
          if (res.data.status == 200) {
            let treeDataList = [];
            Utility.createTreeData(res.data.response, treeDataList);
            self.data = treeDataList;
            if (treeDataList && treeDataList.length > 0) {
              self.tableIndex = treeDataList[0].id;
              self.$nextTick(() => {
                self.$refs.tree.setCurrentKey(treeDataList[0].id);
              });
              callback && callback();
            } else {
              self.tableIndex = "";
              self.tableList = [];
            }
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        }
      );
      // let self = this
      // self.data = []
      // AjaxCommon("/api/folder?folderType=4", "get", null).then((res) => {
      // 	if (res.data.status == 200) {
      // 		var data = res.data.response
      // 		data = data.map((r) => {
      // 			return {
      // 				id: r.Id,
      // 				label: r.FolderName,
      // 				children: [],
      // 			}
      // 		})
      // 		self.data = data
      // 		setTimeout(() => {
      // 			if (data && data.length > 0) {
      // 				console.log("self...............................")
      // 				self.tableIndex = data[0].id
      // 				self.$nextTick(() => {
      // 					self.$refs.tree.setCurrentKey(data[0].id)
      // 				})
      // 				callback && callback()
      // 			} else {
      // 				self.tableIndex = ""
      // 				self.tableList = []
      // 			}
      // 		}, 1000)
      // 	} else {
      // 		PopupCommon.notify("error", res.data.msg)
      // 	}
      // })
    },
    handleNodeClick(e) {
      this.tableIndex = e.id;
      this.initPage();
    },
    handleSelectionChange(d) {
      console.log(d);
    },
    formInputChange(e) {
      // if (e.filedName == "idCard") {
      // 	const data = CardId.getInfoByCardId(e.value)
      // 	if (data) {
      // 		let newData = e.allData
      // 		newData["birthday"] = data.birthday
      // 		newData["sex"] = data.sex
      // 		this.$refs.form.changeFormValue(newData)
      // 	}
      // }
      console.log(e);
    },
    formInputFolderChange(e) {
      console.log(e, "e...................");
    },
    submit(d) {
      let self = this;
      d.DepartmentId = this.tableIndex;
      if (d.sex) {
        d.sex = parseInt(d.sex);
      } else {
        d.sex = -1;
      }
      if (d.uID) {
        AjaxCommon("/api/User/Put", "put", d)
          .then((res) => {
            if (res.data.status == 200) {
              PopupCommon.notify("success", "操作成功");
              self.initPage();
              self.dialogClose();
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          })
          .catch((err) => {
            PopupCommon.notify("error", err.message);
          });
      } else {
        delete d.uID;
        AjaxCommon("/api/User/Post", "post", d)
          .then((res) => {
            if (res.data.status == 200) {
              var id = res.data.response;
              var params = {
                UserId: id,
                TissueID: self.tableIndex,
              };
              AjaxCommon("/api/UserTissueRelation", "postForm", params).then(
                (r) => {
                  if (r.data.status == 200) {
                    PopupCommon.notify("success", "操作成功");
                    self.initPage();
                    self.dialogClose();
                  } else {
                    PopupCommon.notify("error", r.data.msg);
                  }
                }
              );
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          })
          .catch((err) => {
            PopupCommon.notify("error", err.message);
          });
      }
    },
    dialogClose() {
      this.dialogShow = false;
    },
    searchClick() {
      this.pageNo = 1;
      this.initPage();
    },
    resetClick() {
      this.username = "";
      this.usersex = "";
    },
    addClick() {
      if (this.tableIndex == "") {
        PopupCommon.notify(
          "info",
          "请先选择组织机构，如无组织机构，请先新增。"
        );
        return;
      }

      let formConfigItem = this.formConfigAdd;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = "";
          }
        });
      });
      this.formConfigAdd = formConfigItem;
      this.type = "add";
      this.dialogShow = true;
      this.dialogTitle =
        "新增" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    // 分页点击事件
    pageChange(p) {
      this.pageNo = p;
      this.initPage();
    },
    resetPwdRow(d) {
      let self = this;
      PopupCommon.confirm("确定要重置密码?重置后密码为：123456")
        .then(() => {
          var data = d.data;
          var newData = {};
          newData.uID = data.Id;
          newData.uLoginPWD = "123456";
          AjaxCommon("/api/User/Put", "put", newData)
            .then((res) => {
              if (res.data.status == 200) {
                PopupCommon.notify("success", "重置成功");
                self.initPage();
              } else {
                PopupCommon.notify("error", res.data.msg);
              }
            })
            .catch((err) => {
              PopupCommon.notify("error", err.message);
            });
        })
        .catch(() => {
          // 这里尽量写下，否则会报警告异常。
          console.log("已取消重置");
        });
    },
    editRow(d) {
      console.log(d.data, "data.......");
      console.log(this.data, "data........");
      // DepartmentId  Id
      this.oldUserData = d.data;
      this.treeSelectList = this.data;
      this.form.uID = d.data.Id;
      this.form.parentId = d.data.DepartmentId;
      this.form.uLoginName = d.data.LoginName;
      this.form.uRealName = d.data.RealName;
      this.form.sex = d.data.Sex;
      console.log(this.form, "  this.form.....");
      this.dialogFolderEditShow = true;
    },
    viewRow(d) {
      this.type = "look";
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = d.data[t[res]];
          }
        });
      });
      this.formConfig = formConfigItem;
      this.dialogShow = true;
      this.dialogTitle =
        "查看" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    deleteRow(d) {
      const id = d.data.Id;
      console.log(d, "debugger.....");
      let self = this;
      // `api/UserTissueRelation/Delete?TissueID=${d.data.DepartmentId}&UserID=${id}`
      console.log(d.data, "data..........");
      AjaxCommon(
        `api/UserTissueRelation/Delete?TissueID=${d.data.DepartmentId}&UserID=${id}`,
        "delete",
        {
          optReason: d.optReason,
        }
      ).then((res) => {
        if (res.data.status == 200) {
          PopupCommon.notify("success", "删除成功");
          self.initPage();
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    // 初始化事件
    initPage() {
      let self = this;
      var params = `?id=${this.tableIndex}`;
      AjaxCommon("/api/UserTissueRelation" + params, "get", null).then(
        (res) => {
          if (res.data.status == 200) {
            self.dataSource = res.data.response;
            self.pageCount = 1;
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        }
      );
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initLeftFolder(() => {
        this.initPage();
      });
    });
  },
};
</script>

<style scoped>
.flex {
  display: flex;
}

.flex .flex-left {
  width: 350px;
  margin-right: 10px;
}

.flex .flex-right {
  flex: 1;
}

.flex .flex-left .navigationBar {
  height: 36px;
  line-height: 36px;
  background-color: #fff;
  margin-top: 10px;
}

.flex .flex-left .flex-tree {
  background-color: #fff;
  margin-top: 10px;
  height: calc(100vh - 168px);
  overflow-y: auto;
  padding: 10px;
}

.flex .flex-left .flex-tree .tree-item {
  height: 32px;
  line-height: 32px;
  margin: 5px 10px;
  padding: 0 10px;
  font-size: 14px;
  cursor: pointer;
}
.flex .flex-left .flex-tree .tree-item:hover {
  background-color: #e4f1fe;
}
.flex .flex-left .flex-tree .hover {
  background-color: #e4f1fe;
}

.flex .flex-left .navigationBar label {
  text-align: left;
  font-size: 16px;
  color: #333;
  margin-left: 10px;
}

.flex .flex-left .navigationBar span {
  float: right;
  margin-right: 10px;
  color: #333;
  cursor: pointer;
}

.singleTable {
  margin-bottom: 20px;
}
.singleBtn {
  position: absolute;
  bottom: 8px;
  right: 9px;
}
</style>
